<template>
  <div class="apple-permissions-container">
    <div class="apple-page-header glass-effect">
      <h1>用户权限管理</h1>
      <button class="apple-button apple-button-primary button-float" @click="addNewUser">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="12" y1="5" x2="12" y2="19"></line>
          <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
        添加用户
      </button>
    </div>

    <!-- 内容区域 -->
    <div class="apple-tab-container">
      <!-- 已移除用户管理标题 -->
      
      <div class="tab-content">
        <div class="tab-pane">
          <!-- 用户表格 -->
          <div class="apple-table">
            <div class="apple-table-header">
              <div class="apple-table-cell" style="width: 180px">用户名</div>
              <div class="apple-table-cell" style="width: 120px">角色</div>
              <div class="apple-table-cell" style="width: 100px">状态</div>
              <div class="apple-table-cell" style="width: 200px">最后登录</div>
              <div class="apple-table-cell" style="flex: 1">操作</div>
            </div>
            
            <div class="apple-table-body">
              <div 
                v-for="user in filteredUsers" 
                :key="user.id"
                class="apple-table-row"
              >
                <div class="apple-table-cell" style="width: 180px">{{ user.username }}</div>
                <div class="apple-table-cell" style="width: 120px">
                  <el-dropdown @command="(role) => changeUserRole(user.id, role)">
                    <span class="apple-tag clickable" :class="user.roleCode">
                      {{ getRoleLabel(user.role) }} <i class="el-icon-arrow-down"></i>
                  </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-for="role in roles" :key="role.value" :command="role.value">
                          {{ role.label }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="apple-table-cell" style="width: 100px">
                  <span class="apple-status-indicator" :class="user.status">
                    {{ user.status === 'active' ? '启用' : '禁用' }}
                  </span>
                </div>
                <div class="apple-table-cell" style="width: 200px">{{ user.lastLogin }}</div>
                <div class="apple-table-cell" style="flex: 1">
                  <div class="apple-button-group">
                    <button class="apple-button apple-button-small" @click="editUser(user)">
                      编辑
                    </button>
                  <button 
                      class="apple-button apple-button-small" 
                    @click="toggleUserStatus(user)"
                  >
                    {{ user.status === 'active' ? '禁用' : '启用' }}
                  </button>
                    <button 
                      class="apple-button apple-button-small apple-button-danger" 
                      @click="removeUserFromLocation(user.id)"
                    >
                      移除
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div class="apple-pagination">
            <span class="total-text">共 {{ totalUsers }} 条记录</span>
            <div class="pagination-controls">
              <button 
                class="apple-pagination-btn" 
                :disabled="currentPage === 1"
                @click="currentPage--"
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <polyline points="15 18 9 12 15 6"></polyline>
                </svg>
              </button>
              <span class="page-info">{{ currentPage }} / {{ Math.ceil(totalUsers / pageSize) }}</span>
              <button 
                class="apple-pagination-btn" 
                :disabled="currentPage >= Math.ceil(totalUsers / pageSize)"
                @click="currentPage++"
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <polyline points="9 18 15 12 9 6"></polyline>
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户表单对话框 -->
    <div class="apple-modal" v-if="userDialogVisible">
      <div class="modal-overlay" @click="userDialogVisible = false"></div>
      <div class="modal-container glass-effect">
        <div class="modal-header">
          <h2>{{ isEditMode ? '编辑用户' : '添加用户' }}</h2>
          <button class="close-button" @click="userDialogVisible = false">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <form class="apple-form">
            <div class="form-group">
              <label class="apple-form-label" for="username">用户名</label>
              <input 
                id="username"
                type="text" 
                class="apple-form-input" 
                v-model="userForm.username" 
                placeholder="请输入用户名"
                required
              />
            </div>
            
            
            <div class="form-group" v-if="!isEditMode">
              <label class="apple-form-label" for="password">密码</label>
              <input 
                id="password"
                type="password" 
                class="apple-form-input" 
                v-model="userForm.password" 
                placeholder="请输入密码"
                required
                minlength="6"
              />
              <div class="form-help-text">密码长度不能少于6个字符</div>
            </div>
            
            <div class="form-group">
              <label class="apple-form-label" for="role">角色</label>
              <div class="apple-select-wrapper">
                <select 
                  id="role"
                  v-model="userForm.role" 
                  class="apple-select"
                  required
                >
                  <option value="" disabled>请选择角色</option>
                  <option 
                    v-for="role in roles" 
                    :key="role.value" 
                    :value="role.value"
                  >
                    {{ role.label }}
                  </option>
                </select>
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="select-icon">
                  <polyline points="6 9 12 15 18 9"></polyline>
                </svg>
              </div>
              <div class="form-help-text">每种角色的权限是固定的，无法修改</div>
            </div>
            
            <div class="form-group">
              <label class="apple-form-label">状态</label>
              <div class="apple-toggle-switch">
                <input 
                  type="checkbox" 
                  id="status-toggle" 
                  class="toggle-checkbox" 
                  :checked="userForm.status === 'active'"
                  @change="userForm.status = $event.target.checked ? 'active' : 'inactive'"
                />
                <label for="status-toggle" class="toggle-label">
                  <span class="toggle-inner"></span>
                  <span class="toggle-switch"></span>
                </label>
                <span class="toggle-text">{{ userForm.status === 'active' ? '启用' : '禁用' }}</span>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="apple-button" @click="userDialogVisible = false">取消</button>
          <button class="apple-button apple-button-primary button-float" @click="saveUser">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { usePermissionStore } from '../stores/permission'
import { useUserStore } from '../stores/user'
import { useRouter } from 'vue-router'
import { locationsApi } from '../utils/apiService'
import { messageHelper } from '../utils/messageHelper'

// 使用权限store
const permissionStore = usePermissionStore()
const router = useRouter()

// 角色数据
const roles = computed(() => permissionStore.roles)

// 权限组
const permissionGroups = computed(() => permissionStore.permissionGroups)

// 位置用户数据 - 直接从 store 获取，store 内部应处理 API 调用和数据结构
const locationUsers = computed(() => permissionStore.locationUsers)

// 位置用户数据加载状态
const locationsLoading = computed(() => permissionStore.loading)

// 用于权限管理的用户列表
const users = computed(() => {
  console.log('原始位置用户数据:', locationUsers.value);
  // 检查 locationUsers 是否为期望的数组格式
  if (Array.isArray(locationUsers.value) && locationUsers.value.length > 0) {
    console.log('处理位置用户数据，数量:', locationUsers.value.length);
    return locationUsers.value.map(user => {
      // 假设 API 返回的 roleType: 0访客, 1管理员, 2管理者, 3成员
      // 而 roles.value 中的 value 可能也是 0, 1, 2, 3
      const roleValueNum = typeof user.roleType === 'number' ? user.roleType : 0; // 默认访客
      console.log(`处理用户 userId=${user.userId}, 角色值=${roleValueNum}, 类型=${typeof roleValueNum}`);
      
      const roleInfo = roles.value.find(r => r.value === roleValueNum);
      console.log(`找到的角色信息 for ${roleValueNum}:`, roleInfo);

      // 假设没有显式 status 字段，默认 active 或根据需要添加
      const statusValue = user.status || 'active'; // 保持原来的逻辑，如果需要根据 roleType 判断，需修改

      const processedUser = {
        id: user.userId, // 使用 userId
        username: user.nickname || user.username || '未知用户', // 优先使用 nickname
        email: user.email || '-', // API 响应中没有 email，暂时保留
        role: roleInfo ? roleInfo.value : 0, // 使用角色的 value
        roleCode: roleInfo ? roleInfo.code : 'guest', // 使用角色的 code
        status: statusValue, // 假设状态逻辑不变
        lastLogin: user.lastLoginTime || user.lastLogin || '-', // API 响应中没有 lastLogin，暂时保留
        avatar: user.avatar // 新增 avatar 字段，虽然模板没用，但可以保留
      };
      console.log('处理后的用户数据:', processedUser);
      return processedUser;

    });
  } else if (locationUsers.value) {
     console.warn('locationUsers 数据格式不正确或为空:', locationUsers.value);
     return []; // 返回空数组避免错误
  }

  // 如果没有位置用户数据或加载中，返回空数组或处理默认用户
  console.warn('没有有效的位置用户数据，返回空列表');
  // return permissionStore.users.map(user => ({ ... })); // 根据需要决定是否回退
  return [];
})

// 状态变量
const searchQuery = ref('')
const roleFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const userDialogVisible = ref(false)
const isEditMode = ref(false)

// 表单数据
const userForm = reactive({
  id: null,
  username: '',
  email: '',
  password: '',
  role: '',
  status: 'active'
})

// 计算属性
const filteredUsers = computed(() => {
  let result = users.value
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user => 
      user.username.toLowerCase().includes(query) || 
      user.email.toLowerCase().includes(query)
    )
  }
  
  if (roleFilter.value) {
    result = result.filter(user => user.role === roleFilter.value)
  }
  
  return result
})

const totalUsers = computed(() => filteredUsers.value.length)

// 方法
const handleSearch = () => {
  // 搜索时自动重置到第一页
  currentPage.value = 1
}

const handleSearchClear = () => {
  searchQuery.value = ''
}

const handleFilterChange = () => {
  // 筛选变化时自动重置到第一页
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const getRoleLabel = (roleValue) => {
  // 确保roleValue是数字
  const roleValueNum = typeof roleValue === 'string' ? Number(roleValue) : roleValue;
  console.log('获取角色标签，角色值:', roleValueNum, '类型:', typeof roleValueNum);
  
  const role = roles.value.find(r => r.value === roleValueNum);
  console.log('找到的角色:', role);
  
  return role ? role.label : String(roleValue);
}

const getRoleTagType = (role) => {
  switch (role) {
    case 'admin':
      return 'danger'
    case 'manager':
      return 'warning'
    case 'member':
      return 'success'
    case 'guest':
      return 'info'
    default:
      return ''
  }
}

const getPermissionLabel = (permissionValue) => {
  for (const group of permissionGroups.value) {
    const permission = group.permissions.find(p => p.value === permissionValue)
    if (permission) {
      return permission.label
    }
  }
  return permissionValue
}

const addNewUser = () => {
  isEditMode.value = false
  Object.keys(userForm).forEach(key => {
    userForm[key] = key === 'status' ? 'active' : ''
  })
  userDialogVisible.value = true
}

const editUser = (user) => {
  isEditMode.value = true
  Object.keys(userForm).forEach(key => {
    if (key !== 'password') {
      userForm[key] = user[key]
    }
  })
  userDialogVisible.value = true
}

const saveUser = async () => {
  try {
    let result;
    
    // 获取当前位置ID
    const locationId = router.currentRoute.value.params.locationId || permissionStore.currentLocationId;
    
  if (isEditMode.value) {
      result = await permissionStore.updateUser(userForm);
      ElMessage.success('用户信息已更新');
  } else {
      // 准备用户数据，包括位置ID和角色
      const userData = {
        username: userForm.username,
        password: userForm.password,
        email: userForm.email,
        roleType: userForm.role,
        locationId: locationId // 包含位置ID
      };
      
      // 调用用户注册API
      try {
        // 导入usersApi
        const { usersApi } = await import('../utils/apiService');
        result = await usersApi.register(userData);
        
        if (result && result.userId) {
          // 如果注册成功且返回了userId，将用户添加到位置
          try {
            await locationsApi.addUserToLocation({
              userId: result.userId,
              locationId: locationId,
              roleType: userForm.role,
              username: userForm.username,
              password: userForm.password,
              email: userForm.email
            });
            
            // 重新获取位置用户列表以刷新数据
            await permissionStore.fetchLocationUsers(locationId);
            
            ElMessage.success('用户已创建并添加到当前位置');
          } catch (error) {
            console.error('将用户添加到位置失败:', error);
            ElMessage.warning('用户已创建，但添加到位置失败，请重试');
          }
        } else {
          // 如果API返回中没有userId，使用store方法作为备选
          result = await permissionStore.addUser(userForm);
          ElMessage.success('用户已创建');
  }
      } catch (error) {
        console.error('用户注册失败:', error);
        // 如果API调用失败，使用store方法作为备选
        result = await permissionStore.addUser(userForm);
        
        if (locationId && result && result.userId) {
          // 将新创建的用户添加到当前位置
          try {
            await locationsApi.addUserToLocation({
              userId: result.userId,
              locationId: locationId,
              roleType: userForm.role,
              username: userForm.username,
              password: userForm.password,
              email: userForm.email
            });
            
            // 重新获取位置用户列表以刷新数据
            await permissionStore.fetchLocationUsers(locationId);
            
            ElMessage.success('用户已创建并添加到当前位置');
          } catch (error) {
            console.error('将用户添加到位置失败:', error);
            ElMessage.warning('用户已创建，但添加到位置失败，请重试');
          }
        } else {
          ElMessage.success('用户已创建');
        }
      }
    }
    
    userDialogVisible.value = false;
  } catch (error) {
    console.error('保存用户失败:', error);
    ElMessage.error('操作失败: ' + (error.message || '未知错误'));
  }
}

const toggleUserStatus = (user) => {
  permissionStore.toggleUserStatus(user.id)
  ElMessage.success(`用户 ${user.username} 已${user.status === 'active' ? '启用' : '禁用'}`)
}

const deleteUser = (userId) => {
  ElMessageBox.confirm(
    '确定要删除此用户吗？此操作无法撤销。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      permissionStore.deleteUser(userId)
      ElMessage.success('用户已删除')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 处理用户角色变更
const changeUserRole = async (userId, newRoleValue) => {
  try {
    console.log(`更改用户 ${userId} 角色为 ${newRoleValue}`)
    
    // 获取用户原始角色
    const user = locationUsers.value.find(u => u.id === userId)
    if (!user) {
      ElMessage.error('找不到指定用户')
      return
    }
    
    const oldRoleValue = user.role
    const oldRoleLabel = getRoleLabel(oldRoleValue)
    const newRoleLabel = getRoleLabel(newRoleValue)
    
    // 获取位置信息和当前操作用户
    const locationId = router.currentRoute.value.params.locationId || permissionStore.currentLocationId
    const locationInfo = await locationsApi.getLocationById(locationId)
    const locationName = locationInfo?.name || '未知位置'
    
    // 获取当前登录用户
    const userStore = useUserStore()
    const currentUser = userStore.user
    
    // 更新用户角色
    await permissionStore.updateUserRole(userId, locationId, newRoleValue)
    
    // 记录权限变更消息和活动
    await messageHelper.createPermissionChangeNotification(
      user, 
      locationName, 
      locationId, 
      oldRoleLabel, 
      newRoleLabel, 
      currentUser
    )
    
    // 记录权限变更活动
    await messageHelper.recordPermissionChange(
      user,
      locationName,
      locationId,
      oldRoleLabel,
      newRoleLabel,
      currentUser
    )
    
    ElMessage.success(`已将用户 ${user.username} 的角色从 ${oldRoleLabel} 更改为 ${newRoleLabel}`)
  } catch (error) {
    console.error('更改用户角色失败:', error)
    ElMessage.error('更改用户角色失败: ' + (error.message || '未知错误'))
  }
}

// 修改删除用户权限函数，添加消息记录
const removeUserFromLocation = async (userId) => {
  try {
    // 获取用户信息
    const user = locationUsers.value.find(u => u.id === userId)
    if (!user) {
      ElMessage.error('找不到指定用户')
      return
    }
    
    // 获取位置信息和当前操作用户
    const locationId = router.currentRoute.value.params.locationId || permissionStore.currentLocationId
    const locationInfo = await locationsApi.getLocationById(locationId)
    const locationName = locationInfo?.name || '未知位置'
    
    // 获取当前登录用户
    const userStore = useUserStore()
    const currentUser = userStore.user
    
    const result = await ElMessageBox.confirm(
      `确定要从当前位置移除用户 ${user.username} 吗？此操作将撤销该用户对此位置的全部访问权限。`,
      '移除用户确认',
      {
        confirmButtonText: '确定移除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 移除用户权限
    await locationsApi.removeUserFromLocation(userId, locationId)
    
    // 重新获取位置用户列表
    await permissionStore.fetchLocationUsers(locationId)
    
    // 记录消息和活动
    await messageHelper.createUserRemovedFromLocationNotification(
      user,
      locationName,
      locationId,
      currentUser
    )
    
    // 记录活动
    await messageHelper.recordActivity({
      title: '撤销用户权限',
      content: `用户${currentUser.name || currentUser.username}将${user.name || user.username}从${locationName}中移除`,
      actionType: 'permission',
      userName: currentUser.name || currentUser.username,
      locationName: locationName,
      locationId: locationId
    })
    
    ElMessage.success(`已将用户 ${user.username} 从当前位置移除`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除用户失败:', error)
      ElMessage.error('移除用户失败: ' + (error.message || '未知错误'))
    }
  }
}

// 需要确保在组件挂载时调用 store action 获取数据
onMounted(async () => {
  // 假设从路由参数或其他地方获取 locationId
  const locationId = router.currentRoute.value.params.locationId || permissionStore.currentLocationId; // 示例：获取当前位置 ID
  if (locationId) {
    console.log(`Permissions.vue: Fetching users for location ${locationId}`);
    try {
      // 调用 store action 来获取数据，action 内部处理 apiService 调用
      await permissionStore.fetchLocationUsers(locationId);
      console.log('位置用户数据获取成功');
    } catch (error) {
      console.error('获取位置用户数据失败:', error);
      ElMessage.error('加载用户列表失败');
    }
  } else {
    console.warn('无法获取 locationId，跳过用户数据加载');
    // 可以选择加载默认用户或显示提示
  }
  // 可能还需要加载角色信息等
  if (!roles.value || roles.value.length === 0) {
     await permissionStore.fetchRoles(); // 假设有获取角色的 action
  }
});
</script>

<style scoped>
.apple-permissions-container {
  padding: 0px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.apple-page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  margin-bottom: 1px;
  background-color: rgba(255, 255, 255, 0.9);
}

.apple-section-title {
  font-size: 1.5rem;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.glass-effect {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.apple-tab-container {
  flex: 1;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  margin: 0;
  padding: 30px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.apple-tabs {
  display: flex;
  background-color: #f5f5f7;
  border-radius: 10px;
  padding: 5px;
  margin-bottom: 25px;
}

.apple-tab {
  padding: 12px 20px;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.15s ease-in-out;
}

.apple-tab:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.apple-tab.active {
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.tab-content {
  flex: 1;
  overflow: auto;
}

.tab-pane {
  height: 100%;
}

.apple-controls-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.search-box {
  flex: 1;
  position: relative;
}

.apple-search-input {
  width: 100%;
  padding: 12px 40px 12px 15px;
  border: none;
  border-radius: 10px;
  background-color: #f5f5f7;
  font-size: 14px;
  transition: background-color 0.15s ease-in-out;
}

.apple-search-input:focus {
  background-color: #ebebed;
  outline: none;
}

.clear-search {
  position: absolute;
  top: 50%;
  right: 12px;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #8e8e93;
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
  line-height: 1;
  border-radius: 50%;
}

.clear-search:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: #636366;
}

.filter-box {
  display: flex;
  gap: 10px;
}

.apple-select-wrapper {
  position: relative;
  width: 200px;
}

.apple-select {
  width: 100%;
  padding: 12px 40px 12px 15px;
  border: none;
  border-radius: 10px;
  background-color: #f5f5f7;
  font-size: 14px;
  appearance: none;
  color: #1d1d1f;
}

.apple-select:focus {
  background-color: #ebebed;
  outline: none;
}

.select-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
  color: #8e8e93;
}

/* 表格样式 */
.apple-table {
  width: 100%;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.apple-table-header {
  display: flex;
  background-color: #f5f5f7;
  padding: 15px 20px;
  font-weight: 500;
  color: #636366;
}

.apple-table-body {
  max-height: calc(100vh - 380px);
  overflow-y: auto;
}

.apple-table-row {
  display: flex;
  padding: 15px 20px;
  border-bottom: 1px solid #f5f5f7;
  transition: background-color 0.15s ease-in-out;
}

.apple-table-row:last-child {
  border-bottom: none;
}

.apple-table-row:hover {
  background-color: #f9f9f9;
}

.apple-table-cell {
  display: flex;
  align-items: center;
}

.apple-tag {
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.apple-tag.admin {
  background-color: #ff3b30;
  color: white;
}

.apple-tag.manager {
  background-color: #ff9500;
  color: white;
}

.apple-tag.member {
  background-color: #34c759;
  color: white;
}

.apple-tag.guest {
  background-color: #8e8e93;
  color: white;
}

.apple-status-indicator {
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.apple-status-indicator.active {
  background-color: #e6f7ea;
  color: #34c759;
}

.apple-status-indicator.inactive {
  background-color: #f1f1f1;
  color: #8e8e93;
}

.action-cell {
  display: flex;
  gap: 10px;
}

.apple-table-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  background-color: #f5f5f7;
  color: #636366;
  cursor: pointer;
  transition: all 0.15s ease-in-out;
}

.apple-table-btn:hover {
  background-color: #ebebed;
}

.apple-table-btn.edit {
  background-color: #e4f1fe;
  color: #0071e3;
}

.apple-table-btn.edit:hover {
  background-color: #d0e6fc;
}

.apple-table-btn.enable {
  background-color: #e6f7ea;
  color: #34c759;
}

.apple-table-btn.enable:hover {
  background-color: #d1f1db;
}

.apple-table-btn.disable {
  background-color: #f1f1f1;
  color: #8e8e93;
}

.apple-table-btn.disable:hover {
  background-color: #e6e6e6;
}

.apple-table-btn.delete {
  background-color: #fff2f1;
  color: #ff3b30;
}

.apple-table-btn.delete:hover {
  background-color: #ffe1df;
}

.description-cell {
  color: #636366;
  font-size: 13px;
}

.permissions-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.permission-pill {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  background-color: #f5f5f7;
  color: #636366;
}

/* 分页样式 */
.apple-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.total-text {
  color: #8e8e93;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.apple-pagination-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: 50%;
  background-color: #f5f5f7;
  color: #1d1d1f;
  cursor: pointer;
  transition: background-color 0.15s ease-in-out;
}

.apple-pagination-btn:hover:not(:disabled) {
  background-color: #ebebed;
}

.apple-pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #636366;
}

/* 按钮样式 */
.apple-button {
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  background-color: #f5f5f7;
  color: #1d1d1f;
  cursor: pointer;
  transition: all 0.15s ease-in-out;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.apple-button:hover {
  background-color: #ebebed;
}

.apple-button-primary {
  background-color: #0071e3;
  color: white;
}

.apple-button-primary:hover {
  background-color: #0262c3;
}

.button-float {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 模态框样式 */
.apple-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5px);
}

.modal-container {
  position: relative;
  width: 500px;
  max-width: 95%;
  max-height: 95vh;
  overflow-y: auto;
  background-color: white;
  border-radius: 16px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f5f5f7;
}

.modal-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  color: #8e8e93;
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  background-color: #f5f5f7;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #f5f5f7;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表单样式 */
.apple-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.apple-form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
}

.apple-form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #d1d1d6;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.15s ease-in-out;
}

.apple-form-input:focus {
  border-color: #0071e3;
  outline: none;
}

.form-help-text {
  margin-top: 5px;
  font-size: 12px;
  color: #8e8e93;
}

/* 开关样式 */
.apple-toggle-switch {
  display: flex;
  align-items: center;
}

.toggle-checkbox {
  height: 0;
  width: 0;
  visibility: hidden;
  position: absolute;
}

.toggle-label {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  width: 50px;
  height: 26px;
  background: #d1d1d6;
  border-radius: 100px;
  position: relative;
  transition: background-color 0.2s;
}

.toggle-label .toggle-inner {
  width: 22px;
  height: 22px;
  border-radius: 45px;
  background: #fff;
  position: absolute;
  top: 2px;
  left: 2px;
  transition: 0.2s;
  box-shadow: 0 0 2px 0 rgba(10, 10, 10, 0.29);
}

.toggle-checkbox:checked + .toggle-label {
  background: #34c759;
}

.toggle-checkbox:checked + .toggle-label .toggle-inner {
  left: calc(100% - 2px);
  transform: translateX(-100%);
}

.toggle-text {
  margin-left: 10px;
  font-size: 14px;
}

/* 角色权限编辑 */
.role-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 5px 0;
}

.role-description {
  color: #636366;
  margin: 0 0 20px 0;
}

.permissions-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.permission-section {
  background-color: #f9f9f9;
  border-radius: 10px;
  padding: 15px;
}

.permission-group-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px 0;
  color: #1d1d1f;
}

.permissions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.apple-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  cursor: pointer;
}

.apple-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  border-radius: 4px;
  border: 1px solid #d1d1d6;
  transition: all 0.15s ease-in-out;
}

.apple-checkbox input[type="checkbox"]:checked {
  background-color: #0071e3;
  border-color: #0071e3;
}

.apple-checkbox .checkbox-label {
  color: #1d1d1f;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .apple-page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .apple-tab-container {
    padding: 20px;
  }
  
  .apple-controls-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .apple-select-wrapper {
    width: 100%;
  }
  
  .apple-table-header, .apple-table-row {
    padding: 12px 15px;
  }
  
  .permissions-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 576px) {
  .apple-table {
    display: block;
    overflow-x: auto;
  }
  
  .apple-table-header, .apple-table-row {
    min-width: 940px;
  }
}

@media (max-height: 700px) {
  .apple-table-body {
    max-height: calc(100vh - 350px);
  }
}
</style> 
